from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QMessageBox
import logging
import sys
import threading

from model.model import Model
from view.mainwindow import MainWindow

import config

logger = logging.getLogger(__name__)

def install_global_excepthook():
	""" Installs a global excepthook that is used by all threads, by monkey patching
	__init__ in threading.Thread. see issue http://bugs.python.org/issue1230540 """
	init_old = threading.Thread.__init__

	def init(self, *args, **kwargs):
		init_old(self, *args, **kwargs)
		run_old = self.run

		def run_with_except_hook(*args, **kw):
			try:
				run_old(*args, **kw)
			except (KeyboardInterrupt, SystemExit):
				raise
			except:
				sys.excepthook(*sys.exc_info())

		self.run = run_with_except_hook
		threading.Thread.__init__ = init

def excepthook(exc_type, exc_value, traceback):
	logger.error("Uncaught exception", exc_info=(exc_type, exc_value, traceback))
	sys.exit(1)

def main():
	logging.basicConfig(filename='logfile.log', format="%(asctime)s - %(levelname)s: %(message)s",
						level=config.loglevel)
	sys.excepthook = excepthook
	install_global_excepthook()
	model = Model()
	app = QtGui.QApplication(sys.argv)
	clipboard = app.clipboard()
	window = MainWindow(model, clipboard)
	window.resize(450, 500)
	window.move(300, 300)
	window.setWindowTitle("Typesetting Helper")
	window.set_taskbar_text("TSH")
	if config.always_on_top:
		window.setWindowFlags(window.windowFlags() | QtCore.Qt.WindowStaysOnTopHint)
	# has to be done *after* updating the window flags.. changes hwnd presumably?
	window.register_hotkey()

	window.show()
	app.exec_()

if __name__ == "__main__":
	main()
